/**
 * @file       thread_func.hpp
 * @author     WMQ
 * @date       2024/12/29
 * @brief      线程相关操作
 */

#ifndef THREAD_FUNC_HPP
#define THREAD_FUNC_HPP

#include <cstdint>
#include <thread>
#if defined(_WIN32)
    #include <windows.h>
#elif defined(__linux__)
    #include <sys/syscall.h>
    #include <unistd.h>
#endif

namespace ThreadFunc {

/**
 * @brief 获取当前进程id
 */
inline int64_t GetProcessId()
{
#if defined(_WIN32)
    return static_cast<int64_t>(GetCurrentProcessId());
#elif defined(__linux__)
    return static_cast<int64_t>(getpid());
#endif
    return 0;
}

/**
 * @brief 获取当前线程id
 */
inline int64_t GetThreadId()
{
#if defined(_WIN32)
    return static_cast<int64_t>(GetCurrentThreadId());
#elif defined(__linux__)
    return static_cast<int64_t>(syscall(SYS_gettid));
#endif
    return 0;
}

/**
 * @brief 将线程sleep
 * @param[in] milliseconds sleep的时间，单位ms
 * @note
 *   注意sleep时间误差，一般系统函数提供的函数sleep(1ms)误差较大
 */
inline void SleepFor(uint32_t milliseconds)
{
#if defined(_WIN32)
    Sleep(milliseconds);
#elif defined(__linux__)
    usleep(milliseconds * 1000);
#else
    std::this_thread::sleep_for(std::chrono::milliseconds(milliseconds));
#endif
}
} // namespace ThreadFunc

#endif